package runtime

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type HttpServer struct {
	*gin.Engine
	httpSrv *http.Server
	host    string
	port    int
	logger  *slog.Logger
	name    string
}

func (h *HttpServer) Name() string {
	return fmt.Sprintf("%s 端口：%d", h.name, h.port)
}

type Option func(*HttpServer)

func NewHttpServer(engine *gin.Engine, host string, port int, logger *slog.Logger) *HttpServer {
	return &HttpServer{
		Engine: engine,
		host:   host,
		port:   port,
		logger: logger,
		name:   "http服务",
	}
}

// SetName 设置服务名称
func (s *HttpServer) SetName(name string) {
	s.name = name
}

func (s *HttpServer) Start(_ context.Context) error {

	s.httpSrv = &http.Server{
		Addr:    fmt.Sprintf("%s:%d", s.host, s.port),
		Handler: s,
	}

	if err := s.httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
		panic(err)
	}
	return nil

}

func (s *HttpServer) Stop(_ context.Context) error {
	s.logger.Info("Shutting down server...")

	// The context is used to inform the server it has 5 seconds to finish
	// the request it is currently handling
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := s.httpSrv.Shutdown(ctx); err != nil {
		panic(err)

	}

	s.logger.Info("Server exiting")
	return nil
}
